package com.huawang.mdesign.model.service.util.reqif.converter;

import cn.hutool.core.date.DateUtil;
import com.thoughtworks.xstream.converters.basic.AbstractSingleValueConverter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TimeZone;

/**
 * @author xdl
 * @since 2023-04-04
 */
public class DateConverter extends AbstractSingleValueConverter {

    private static final String DATE_TIME_PATTERN = "yyyy-MM-dd'T'HH:mm:ss";

    @Override
    public boolean canConvert(Class type) {
        return type.equals(Date.class);
    }

    @Override
    public Object fromString(String str) {
        if (str == null || "".equals(str)) {
            return null;
        }
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_PATTERN);
        sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
        try {
            return sdf.parse(str);
        } catch (ParseException e) {
            return new Date();
        }
    }

    @Override
    public String toString(Object obj) {
        if (obj == null) {
            return "";
        }
        try {
            SimpleDateFormat sdf = new SimpleDateFormat(DATE_TIME_PATTERN);
            sdf.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
            return sdf.format((Date) obj);
        }catch (IllegalArgumentException e){
            return DateUtil.now();
        }
    }
}
